//
//  YYTextView+MHExtension.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/10/8.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "YYTextView+MHExtension.h"

@implementation YYTextView (MHExtension)


- (BOOL)textView:(YYTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text maxLength:(NSInteger)maxLength {
    NSMutableString *str = textView.text.mutableCopy;
    if (!str)  str = @"".mutableCopy;
    [str replaceCharactersInRange:range withString:text];
    if (str.length > maxLength) {
        [UIWindow showTips:[NSString stringWithFormat:@"最多可输入%ld个字符",(long)maxLength]];
        return NO;
    }
    return YES;
}

- (void)mh_limitMaxLength:(NSInteger)maxLength {
    
    UITextRange *selectedRange = [self markedTextRange];
    UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制,防止中文被截断
//    if (position) return ;
    if (self.text.length <= maxLength) return;
    //中文和emoj表情存在问题，需要对此进行处理
    NSRange range;
    NSUInteger inputLength = 0;
    for(int i =0 ; i < self.text.length && inputLength <= maxLength; i += range.length){
        range = [self.text rangeOfComposedCharacterSequenceAtIndex:i];
        inputLength += [self.text substringWithRange:range].length;
        if (inputLength > maxLength)
        {
            [UIWindow showTips:[NSString stringWithFormat:@"最多可输入%ld个字符",(long)maxLength]];
            self.text = [self.text substringWithRange:NSMakeRange(0, range.location)];
        }
    }
}
@end
